//
//  AppDelegate.swift
//  Kool Car
// 
//  Created by huangweiqiang on 2021/12/14.
//

import UIKit
//import FlexLib
import IQKeyboardManager
import FacebookCore


let kScreenWidth = UIScreen.main.bounds.size.width
let kScreenHeight = UIScreen.main.bounds.size.height

@main
class AppDelegate: UIResponder, UIApplicationDelegate {
    var window: UIWindow?
    var sys_launchView: UIView!
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // GMSServices.provideAPIKey("AIzaSyBBRjSkhWTA0HdIrHpwdEb_ZIqlnopLPVY")
        //GMSPlacesClient.provideAPIKey("AIzaSyBBRjSkhWTA0HdIrHpwdEb_ZIqlnopLPVY")
 
        self.window = UIWindow.init(frame: UIScreen.main.bounds)
        self.stopDartStyle()
        self.initKeyboardManager() //键盘
        //搜索历史记录fmdb
        LLKeyValueStore.share()?.createDB(withTableName: XTManageCenter.SearchHistoryTable)
        self.initJpush(launchOptions: launchOptions)
        
        let vc = LaunchAdvViewController()
        self.window?.rootViewController = vc
//        self.requestBaseParameter()
//        let isFristOpen = XTManageCenter.getLocalStringDataValue(aKey: UtilCenter.isFristOpen)//是否引导页
//        if isFristOpen == "" {
//            //进入引导页
//            let vc = GuidePageViewController()
//            self.window?.rootViewController = UINavigationController.init(rootViewController: vc)
//        }else{
//            let tabbarVC = BaseTabbarController()
//            self.window?.rootViewController = tabbarVC
//            tabbarVC.selectedIndex = 0
//        }
        self.window?.makeKeyAndVisible()
        
        //Facebook
//        ApplicationDelegate.shared.application(
//            application,
//            didFinishLaunchingWithOptions: launchOptions
//        )
        return true
    }
    
    func stopDartStyle() {
        // 强制关闭暗黑模式
        if #available(iOS 13, *) {
            self.window?.overrideUserInterfaceStyle = .light
        }
    }
    
    private func requestBaseParameter() {
        XTRequestCenter.shared.sendRequestMappableTargetObject(target: APIManager.baseParameter(param: ["":""]), objectType: BaseParameterModel.self) { data in
            let resultObj = data as! BaseParameterModel
            if resultObj.code == "1" && resultObj.data != nil {
                XTManageCenter.setLocalPlaceParameter(paramData: resultObj.data)
            }else{
                
            }
        } error: { err in
            
        }
    }
    
    //键盘管理初始化
    func initKeyboardManager() {
        IQKeyboardManager.shared().isEnabled = true
        //控制点击背景是否收起键盘
        IQKeyboardManager.shared().shouldResignOnTouchOutside = true
        //控制键盘上的工具条文字颜色是否用户自定义
        IQKeyboardManager.shared().shouldShowToolbarPlaceholder = true
        // IQKeyboardManager.sharedManager().shouldToolbarUsesTextFieldTintColor = true
        //将右边Done改成完成
        IQKeyboardManager.shared().toolbarDoneBarButtonItemText = "完成"
        // 控制是否显示键盘上的工具条
        IQKeyboardManager.shared().isEnableAutoToolbar = false
        //最新版的设置键盘的returnKey的关键字 ,可以点击键盘上的next键，自动跳转到下一个输入框，最后一个输入框点击完成，自动收起键盘
        IQKeyboardManager.shared().toolbarManageBehaviour = .byPosition
        IQKeyboardManager.shared().keyboardDistanceFromTextField = 100
        
    }
    
    func application(
        _ app: UIApplication,
        open url: URL,
        options: [UIApplication.OpenURLOptionsKey : Any] = [:]
    ) -> Bool {
        ApplicationDelegate.shared.application(
            app,
            open: url,
            sourceApplication: options[UIApplication.OpenURLOptionsKey.sourceApplication] as? String,
            annotation: options[UIApplication.OpenURLOptionsKey.annotation]
        )
    }
    
    //初始化JpushSDK
    func initJpush(launchOptions: [UIApplicationLaunchOptionsKey: Any]?){
        
        //【注册通知】通知回调代理（可选）
        let entity = JPUSHRegisterEntity.init()
        entity.types = Int(JPAuthorizationOptions.alert.rawValue | JPAuthorizationOptions.badge.rawValue | JPAuthorizationOptions.sound.rawValue)
        JPUSHService.register(forRemoteNotificationConfig: entity, delegate: self)
        
        JPUSHService.setup(withOption: launchOptions, appKey: XTManageCenter.JPushAppKey, channel: XTManageCenter.JPushChannel, apsForProduction: XTManageCenter.JPushIsProduction, advertisingIdentifier: nil)
        JPUSHService.registrationIDCompletionHandler { (resCode, registrationID) in
            if(resCode == 0){
                printLog("registrationID获取成功:")
                printLog(registrationID)
            }
            else{
                printLog("registrationID获取失败，code")
                printLog(resCode)
            }
        }
        
        //APP未开启时(进程被杀死时)通知
        let notificationDic = launchOptions?[UIApplicationLaunchOptionsKey(rawValue: "UIApplicationLaunchOptionsRemoteNotificationKey")]
        if notificationDic != nil{//处理结果//点击通知栏消息，打开APP，进入消息详情页。如果未登录，则跳转至登录页，登录成功后进入消息详情页。
            
        }
        
    }
    
    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        JPUSHService.registerDeviceToken(deviceToken)
        JPUSHService.registrationIDCompletionHandler { (resCode, registrationID) in
            printLog(registrationID)
//            XTManageCenter.setLocalDataString(aKey: XTManageCenter.kXTUUID, aValue: registrationID ?? "")
        }
    }
    
//    //推送到来的时候第一个调用的方法：
//    @available(iOS 13.0.0, *)
//    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any]) async -> UIBackgroundFetchResult {
//
//    }
    
//
//    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
//
//    }
    
    
    func applicationDidEnterBackground(_ application: UIApplication) {
        //清空通知小红点
        UIApplication.shared.applicationIconBadgeNumber = 0
        JPUSHService.setBadge(0)
    }
    
    func applicationWillEnterForeground(_ application: UIApplication) {
        // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
        //清空通知小红点
        application.applicationIconBadgeNumber = 0
        application.cancelAllLocalNotifications()
        JPUSHService.setBadge(0)
        
        ///首页启动时加载
        let rootVC = UIApplication.shared.keyWindow?.rootViewController
        if (rootVC as? BaseTabbarController) != nil && (rootVC?.childViewControllers ?? []).count > 0 {
            let mainNavi = rootVC?.childViewControllers.first as! BaseNavigationController
            guard let mainVC = mainNavi.viewControllers.first as? BuyCarsViewController else {
                return
            }
            mainVC.applicationWillEnterForeground()
        }
    }
    
    
}


extension AppDelegate: JPUSHRegisterDelegate{
    
    func jpushNotificationAuthorization(_ status: JPAuthorizationStatus, withInfo info: [AnyHashable : Any]?) {
        
    }
    
    
    @available(iOS 12.0, *)
    func jpushNotificationCenter(_ center: UNUserNotificationCenter, openSettingsFor notification: UNNotification) {
        //代理要执行的
    }
    
    //APP在前台运行时收到通知的处理
    @available(iOS 10.0, *)
    func jpushNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: ((Int) -> Void)) {
        let userInfo = notification.request.content.userInfo
        let request = notification.request// 收到推送的请求
        let content = request.content//收到推送的消息内容
        let badge = content.badge//推送消息的角标
        let body = content.body//推送消息体
        let subtitle = content.subtitle  // 推送消息的副标题
        let title = content.title  // 推送消息的标题
        if notification.request != nil && notification.request.trigger != nil {
            if (notification.request.trigger?.isKind(of: UNPushNotificationTrigger.self))! {
                JPUSHService.handleRemoteNotification(userInfo)
            }
        }
        UIApplication.shared.applicationIconBadgeNumber = 0
        JPUSHService.setBadge(0)
        completionHandler(0) // 需要执行这个方法，选择是否提醒用户，有 Badge、Sound、Alert 三种类型可以选择设置
    }
    
    //APP进入后台(未结束进程)时
    @available(iOS 10.0, *)
    func jpushNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: (() -> Void)) {
        let userInfo = response.notification.request.content.userInfo 
        
        let request = response.notification.request// 收到推送的请求
        let content = request.content//收到推送的消息内容
        let badge = content.badge//推送消息的角标
        let body = content.body//推送消息体
        let subtitle = content.subtitle  // 推送消息的副标题
        let title = content.title  // 推送消息的标题
        NotificationCenter.default.post(name: NSNotification.Name(XTManageCenter.JpushMsgType), object: nil,userInfo: ["msgType": "1"])
        
        if let type = userInfo["msgType"] as? String{
            let id = userInfo["id"] as? String
            NotificationCenter.default.post(name: NSNotification.Name(XTManageCenter.JpushMsgType), object: nil,userInfo: ["msgType": type,"id": id as Any])
        }
        
        if response.notification.request != nil && response.notification.request.trigger != nil {
            if (response.notification.request.trigger?.isKind(of: UNPushNotificationTrigger.self))! {
                JPUSHService.handleRemoteNotification(userInfo)
            }
        }
        UIApplication.shared.applicationIconBadgeNumber = 0
        JPUSHService.setBadge(0)
    }
    
}

      

